let table, form;
let orgId = getQueryString('orgId');
let cateCheckIds = new Array();
let checkedTable = new Array();
let cancelArr = new Array();
const arr = new Array();

layui.use(['table', 'form'], function () {
    table = layui.table;
    form = layui.form;


    //1)加载分类复选框
    $.ajax({
        url: '/sys-org-cate/getList'
        , type: 'post'
        , async: false
        , data: {'socState': 1}
        , success: function (res) {
            if (res.code == 0) {
                if (res.data && res.data.length > 0) {
                    let html = '';
                    for (let i of res.data) {
                        arr.push(i.id);
                        html += `<input type="checkbox" name="${i.id}" lay-filter="test1" title="${i.socName}" lay-skin="primary" checked>`;
                    }
                    //加载分类复选框
                    $('#cateSelect').append(html);

                    form.render();

                    let w = 0;
                    let h = 0;
                    $("#cateSelect div").each(function () {
                        let wd = $(this).css('width');
                        let width = parseInt(wd.substring(0, wd.length - 2));

                        w += width;
                    });

                    //checkbox 渲染后的div总宽度大于603则进行折行操作
                    if (w >= 603) {
                        let shang = w / 600;
                        h = 50 * shang;
                        if (h < 250) {
                            $('#orgCate').css('height', `${h}px`);
                            $('#cateSelect').css('height', `${h}px`);
                            $('#cateSelect').css('line-height', ``);
                            $('#cate').css('height', `${h}px`);
                            $('#cate').css('line-height', `${h}px`);
                        } else { //当cateSelect的高度达到250px时有滚动条出现
                            $('#orgCate').css('height', `150px`);
                            $('#cateSelect').css('height', `150px`);
                            $('#cateSelect').css('line-height', ``);
                            $('#cateSelect').css('overflow', `auto`);
                            $('#cate').css('height', `150px`);
                            $('#cate').css('line-height', `150px`);
                        }
                    }
                }
            }

        }
    });

    //2）获取选中的机构分类
     let elems = $('#cateSelect').find('input[type=checkbox]').prop('checked',true);

    if (elems && elems.length > 0) {
        for (let i of elems) {
            cateCheckIds.push(parseInt($(i).attr('name')));
        }
        //3)根据选中的分类加载机构表格
        loadOrgTable(cateCheckIds, '');
    }

    //监听全选
    form.on('checkbox(all)',function (data) {
        let checked = data.elem.checked;

        if(checked){
            //首先添加要移除的元素
            if(cancelArr.length > 0){
                for(let i of cancelArr){
                    if(cateCheckIds.indexOf(i) == -1){
                        cateCheckIds.push(i);
                    }
                }
            }

            cateCheckIds = arr;
            $("#cateSelect input").each(function () {
                $(this).prop('checked',true);
            });
            form.render();
        }else{
            cateCheckIds = [];
            $("#cateSelect input").each(function () {
                $(this).prop('checked',false);
            });
            form.render();
        }
        loadOrgTable(cateCheckIds, '');
    });

    //4)监听复选框选中
    form.on('checkbox(test1)', function (data) {

        let checked = data.elem.checked;
        let name = parseInt(data.elem.name);

        if (checked) {
            let arr = new Array(); //1)arr存放所有分类checkbox选中和非选中的值
            $("#cateSelect input").each(function () {
                let checked = $(this).prop('checked');
                if(checked){
                    arr.push('true');
                }else{
                    arr.push('false');
                }
            });

            if(arr.indexOf('false') == -1){ //2）如果arr里面没有false，则全选的CheckBox为选中状态
                $('input[name=switch]').prop('checked',true);
                form.render();
            }

            if (cateCheckIds.indexOf(name) == -1) {
                cateCheckIds.push(name);
            }
        } else {
            if (cateCheckIds.indexOf(name) > -1) {
                cateCheckIds.splice(jQuery.inArray(name, cateCheckIds), 1); //删除数组中所在元素
                cancelArr.push(name);
            }
            $('input[name=switch]').prop('checked',false);
            form.render();
        }

        loadOrgTable(cateCheckIds, '');
    });

});

/**
 * @author wh
 * @desc 根据选中的分类和机构名重载机构表格
 * @param data
 */

$('#search').on('click', function () {
    //1)获取机构名
    let orgName = $('#searchString').val();

    if (orgName && orgName != '' && cateCheckIds && cateCheckIds.length > 0) {
        loadOrgTable(cateCheckIds, orgName);
    } else if (orgName != "" && cateCheckIds && cateCheckIds.length == 0) {
        layer.msg("请选择分类后再查询！", {icon: 5, time: 1500});
    } else {
        loadOrgTable(cateCheckIds,'');
    }
});


function loadOrgTable(ids, orgName) {
    let obj = new Object();
    obj.id = orgId;
    obj.arr = ids;
    if (orgName && orgName != '') {
        obj.orgName = orgName;
    }
    if (ids && ids.length > 0) {
        $.ajax({
            url: '/sys-org/getCompanyByCateIds'
            , type: 'post'
            , async: false
            , traditional: true
            , data: obj
            , success: function (res) {
                if (res.code == 0) {

                    //渲染机构表
                    renderOrgTable(res.data, ids, orgName);

                    //表格监听
                    table.on('checkbox(test2)', function (obj) {
                        switch (obj.type) {
                            case 'all':
                                if (obj.checked) {
                                    checkedTable = res.data;
                                } else {
                                    checkedTable = [];
                                }
                                break;
                            case 'one':
                                if (obj.checked) {
                                    if (checkedTable.indexOf(obj.data) == -1) {
                                        checkedTable.push(obj.data);
                                    }
                                } else {
                                    checkedTable.splice(jQuery.inArray(obj.data, checkedTable), 1); //删除数组中所在元素
                                }
                                break;
                        }
                        //把数据缓存起来
                        if (localStorage.company) {
                            localStorage.removeItem('company');
                        }

                        localStorage.company = JSON.stringify(checkedTable);
                    });


                }
            }
        });
    } else {
        renderOrgTable([], null, null);
    }
}

function renderOrgTable(data, ids, orgName) {
    //渲染机构表格
    table.render({
        elem: '#content'
        , data: data
        , method: 'post'
        , height: 320
        , limit: 8
        , limits: [8, 16, 24, 32, 40, 48, 56, 64, 72, 80]
        , where: {
            'cateList': ids,
            'id': orgId
        }
        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        , cols: [[
            {type: 'checkbox'}
            , {field: 'orgName', title: '机构名称'}
        ]]
        , page: true
        , done: function () {
            $('.layui-table-tool-self').hide();
        }

    });
}

/**
 * @desc 获取url参数
 * @param name
 * @returns {*}
 */
function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    ;
    return null;
}

